package base

import (
	"github.com/giter/go.rice"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/contrib/sessions"
	"gitee.com/dayu1985/can_api/service/base"
	"os"
	"io/ioutil"
	"gitee.com/dayu1985/can_api/controller/app"
	"net/http"
)

var HTTPBox = map[string]*rice.HTTPBox{}
var Box = map[string]*rice.Box{}
var BoxStr = map[string]http.Dir{}

func NewApplication() error {
	initServiceAction()
	initRouterAction()
	return nil
}

//初始化路由
func initRouterAction() {
	//1. gin引擎的启动
	m := gin.Default()
	//m.Use(gzip.Gzip(gzip.BestSpeed))

	//2. 设置session
	store := sessions.NewCookieStore([]byte("can_api.0.0"))
	store.Options(sessions.Options{
		Path:     "/",
		MaxAge:   0,
		HttpOnly: true,
	})
	m.Use(sessions.Sessions("s", store))
	//3. 路由权限配置
	priv := NewPrivilege(m)
	routeContext := &RouteContext{
		Privilege: priv,
	}
	//4. 路由启动
	Route(routeContext)
	//5. 寻找启动端口
	port := app.MustValue("system", "port", "40000")

	//6. https证书服务
	useTLS := app.MustBool("system", "tls", true)
	if useTLS {
		ssl, err := rice.FindBox("conf")
		if err != nil {
			panic(err)
		}
		if _, err := os.Stat("./conf/ssl/server.crt"); os.IsNotExist(err) {
			bs, err := ssl.Bytes("ssl/server.crt")
			if err != nil {
				panic(err)
			}
			os.MkdirAll("./conf/ssl", 0666)
			ioutil.WriteFile("./conf/ssl/server.crt", bs, 0666)
		}

		if _, err := os.Stat("./conf/ssl/server.key"); os.IsNotExist(err) {
			bs, err := ssl.Bytes("ssl/server.key")
			if err != nil {
				panic(err)
			}
			os.MkdirAll("./conf/ssl", 0666)
			ioutil.WriteFile("./conf/ssl/server.key", bs, 0666)
		}
		m.RunTLS(":"+port, "./conf/ssl/server.crt", "./conf/ssl/server.key")
	} else {
		m.Run(":" + port)
	}

}

func initServiceAction() {
	base.NewService()
}
